﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：武双 
    //
    // 文件名：BulidPaymentAdd.cs
    // 文件功能描述：结算管理：新增结算单
    // 创建标识：武双2009-05-12
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections.Generic;
using HZ.DrugTrade.Web;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.Model.Enum;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;

namespace HZ.DrugTrade.Web.Hospitals.Collection
{

    public partial class BulidPaymentAdd : BasePage
    {
        IBLL_Purchase iPurchase = Factory.BLL_Purchase();
        IBLL_Company ic = Factory.BLL_Company();

        public BulidPaymentAdd()
        {
            this.ModuleNo = Module.结算单管理.ToString();
            this.PageOperateType = OperateType.新增.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //txtCompany.Attributes.Add("readonly", "readonly");
            txtInvoice.Attributes.Add("readonly", "readonly");
            txtPayMentName.Attributes.Add("readonly", "readonly");
            txtMoney.Attributes.Add("readonly", "readonly");
            if (!IsPostBack)
            {
                //判断是否有参数传入
                if (Request.QueryString["IID"] != null)
                {
                    BidText(Request.QueryString["IID"].ToString());
                }
                else
                {
                    //获取已选择的企业编号和名称
                    //if (Request.QueryString["companyId"] != null)
                    //{
                    //    string companyId = Request.QueryString["companyId"];
                    //    //结算单名称
                    //    txtPayMentName.Text = AutoName(CurrentAccount.GetUser().Org.OrgName, "", "结算单");
                    //    //企业编号和企业名称
                    //    hfdCompanyID.Value = companyId;
                    //    lblCompanyName.Text = ic.GetCompanyInfoByID(companyId).CompanyName;
                    //    //历史欠款
                    //    lblOweAmount.Text = GetOweAmount(companyId).ToString();
                    //}
                    //else
                    //{
                    //    HZ.Web.WebUtil.Alert("请先选择企业！", this);
                    //    HZ.Web.WebUtil.RedirectByScript("UnPayList.aspx");
                    //}

                    //发票号
                    string recipitIds = Request.QueryString["recipitIds"];
                    //发票流水号
                    string sIds = Request.QueryString["sIds"];
                    //发票总金额
                    decimal money = Convert.ToDecimal(Request.QueryString["money"]);
                    //企业编号
                    string companyId = Request.QueryString["companyid"];

                    //结算单名称
                    txtPayMentName.Text = AutoName(CurrentAccount.GetUser().Org.OrgName, "", "结算单");
                    //企业编号和企业名称
                    hfdCompanyID.Value = companyId;
                    lblCompanyName.Text = ic.GetCompanyInfoByID(companyId).CompanyName;
                    //历史欠款
                    lblOweAmount.Text = GetOweAmount(companyId).ToString();

                    txtInvoice.Text = recipitIds;
                    hidInvoice.Value = sIds.Replace("|", "'").TrimEnd(',');
                    txtMoney.Text = money.ToString("F2");
                    txtActualAmount.Text = money.ToString("F2");

                    //获取所有与发票有关的产品
                    LaIfrom.Text = "<iframe style=' position: relative;'  width='800px' height='300px' scrolling='yes' src=\"InvoicePaydeail.aspx?IDP=" + hidInvoice.Value + "\"> </iframe>";
                }

            }

        }

        /// <summary>
        /// 获取所选企业的历史欠款
        /// </summary>
        /// <param name="companyid">所选企业的编号</param>
        /// <returns></returns>
        private string GetOweAmount(string companyid)
        {
            int totalcount = 0;
            System.Data.DataTable dt = iPurchase.GetHistroyTradeCompany(CurrentAccount.GetUser().Org.OrgID, "", companyid, 1, 0, out totalcount);

            if (dt.Rows.Count == 0)
            {
                return "0.000";
            }
            else
            {
                return dt.Rows[0]["oweAmount"].ToString();
            }
        }
        /// <summary>
        /// 自动生成结算单名称
        /// </summary>
        /// <param name="username"></param>
        /// <param name="splitchar">分隔符</param>
        /// <param name="Typename">名称类型</param>
        /// <returns></returns>
        protected string AutoName(string username, string splitchar, string Typename)
        {
            string autoname = System.DateTime.Now.Year.ToString() + splitchar + System.DateTime.Now.Month.ToString() + splitchar +
             System.DateTime.Now.Day.ToString() + splitchar + System.DateTime.Now.Hour.ToString() + splitchar + System.DateTime.Now.Minute.ToString() + splitchar + System.DateTime.Now.Second.ToString();
            return username + autoname + Typename;
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                AddBidProduct();
            }
        }

        private void AddBidProduct()
        {
            if (hidInvoice.Value != "")
            {
                string hidinvoice = hidInvoice.Value;
                hidinvoice = hidinvoice.Substring(0, hidinvoice.Length - 1);
                LaIfrom.Text = "<iframe style=' position: relative;' width='800px' height='300px' scrolling='yes'  src=\"InvoicePaydeail.aspx?IDP=" + hidinvoice + "\"> </iframe>";
            }
        }
        private void BidText(string PaySerialID)
        {
            int totalDrugrecord = 0;
            Model.Query.InvoicePay aInvoicePay = new Model.Query.InvoicePay();
            aInvoicePay.InvoicePaySerialID = PaySerialID;
            //只有未确认的结算单可以修改，已确认的则不可以
            aInvoicePay.PayStatus = 0;
            IList<Model.View.InvoicePay> lstInvoicePay = new List<Model.View.InvoicePay>();
            lstInvoicePay = iPurchase.GetTotalInvoicePayByWhere(aInvoicePay, 1, 0, out totalDrugrecord);
            if (lstInvoicePay.Count > 0)
            {
                //txtInvoicePayNo.Text = lstInvoicePay[0].InvoicePayNo;
                txtPayMentName.Text = lstInvoicePay[0].InvoicePayName;
                //txtCompany.Text = lstInvoicePay[0].CompanyName_PS;
                lblCompanyName.Text = lstInvoicePay[0].CompanyName_PS;
                hfdCompanyID.Value = lstInvoicePay[0].CompanyID_PS;
                txtRemark.Text = lstInvoicePay[0].Remarks;
                txtMoney.Text = lstInvoicePay[0].PayAmount.ToString();
                //实付总金额
                //txtActualAmount.Text = lstInvoicePay[0].ActualAmount.ToString();
                txtActualAmount.Text = lstInvoicePay[0].PayAmount.ToString();
                //历史欠款
                lblOweAmount.Text = (lstInvoicePay[0].PayAmount - lstInvoicePay[0].ActualAmount).ToString();
            }

            HZ.DrugTrade.Model.Query.InvoiceDistribution qryWhere = new HZ.DrugTrade.Model.Query.InvoiceDistribution();
            HZ.DrugTrade.Model.Query.Invoice qryInvoice = new HZ.DrugTrade.Model.Query.Invoice();
            qryInvoice.InvoicePaySerialID = PaySerialID;
            qryWhere.InvoicePaySerialID = PaySerialID;

            //获取发票号
            IList<Model.View.Invoice> lstInvoice = iPurchase.GetInvoiceByWhere(qryInvoice, 1, 0, out totalDrugrecord);
            txtInvoice.Text = StringUtility.GetModelFieldArrayString(lstInvoice, "InvoiceID", ",", false);
            hidInvoice.Value = StringUtility.GetModelFieldArrayString(lstInvoice, "InvoiceSerialID", ",", true);

            ////获取与该发票有关的所有配送关系
            //IList<Model.View.InvoiceDistribution> lstInvoiceDistribution = new List<Model.View.InvoiceDistribution>();
            //lstInvoiceDistribution = iPurchase.GetInvoiceDistributionByWhere(qryWhere, 1, 0, out totalDrugrecord);
            LaIfrom.Text = "<iframe style=' position: relative;'  width='800px' height='300px' scrolling='yes' src=\"InvoicePaydeail.aspx?IDP=" + hidInvoice.Value + "\"> </iframe>";
        }


        protected void btnSave_Click(object sender, EventArgs e)
        {
            //HZ.Web.WebUtil.RedirectByScript ("BulidPaymentAdd.aspx");
            //if (string.IsNullOrEmpty(this.txtInvoicePayNo.Text.Trim()))
            //{
            //    HZ.Web.WebUtil.Alert("结算单编号不能为空！", this);
            //    return;
            //}
            if (string.IsNullOrEmpty(this.txtPayMentName.Text.Trim()))
            {
                HZ.Web.WebUtil.Alert("结算单名称不能为空！", this);
                return;
            }
            //if (string.IsNullOrEmpty(this.txtCompany.Text.Trim()))
            //{
            //    HZ.Web.WebUtil.Alert("请选择配送企业！",this);
            //    return;
            //}
            if (string.IsNullOrEmpty(this.txtInvoice.Text.Trim()))
            {
                HZ.Web.WebUtil.Alert("请选择发票号！", this);
                return;
            }
            //if (string.IsNullOrEmpty(this.txtMoney.Text.Trim()) || this.txtMoney.Text.Trim().Equals("0"))
            //{
            //    HZ.Web.WebUtil.Alert("发票金额不能为空必须大于0！", this);
            //    return;
            //}
            if (string.IsNullOrEmpty(this.txtActualAmount.Text.Trim()))
            {
                HZ.Web.WebUtil.Alert("实付金额不能为空！", this);
                txtActualAmount.Focus();
                return;
            }

            string InvoicePaySerialID;
            if (!string.IsNullOrEmpty(Request.QueryString["IID"]))
            {
                InvoicePaySerialID = Request.QueryString["IID"].Substring(1, Request.QueryString["IID"].Length-2);
            }
            else
            {
                InvoicePaySerialID = Guid.NewGuid().ToString();
            }

            InvoicePay aInvoicePay = new InvoicePay();
            aInvoicePay.InvoicePayName = txtPayMentName.Text.Trim();
            //aInvoicePay.InvoicePayNo = txtInvoicePayNo.Text.Trim();
            //if (Request.QueryString["IID"] != null)
            //{
            //    InvoicePaySerialID = Request.QueryString["IID"].ToString();
            //}
            aInvoicePay.InvoicePaySerialID = InvoicePaySerialID;
            aInvoicePay.InvoicePayTime = DateTime.Now;
            aInvoicePay.PayAmount = new HZ.Common.ConvertHelper(txtMoney.Text.Trim()).ToDecimal;
            //实付金额
            aInvoicePay.ActualAmount = new HZ.Common.ConvertHelper(txtActualAmount.Text.Trim()).ToDecimal;

            aInvoicePay.PayStatus = 0;
            aInvoicePay.Remarks = txtRemark.Text.Trim();

            IList<Invoice> lstInvoice = new List<Invoice>();
            lstInvoice.Clear();
            //发票流水号
            string hidinvoice = hidInvoice.Value;
            hidinvoice = hidinvoice.Substring(0, hidinvoice.Length - 1);
            //发票号
            string invoiceId = txtInvoice.Text.Trim();
            invoiceId = invoiceId.Substring(0, invoiceId.Length - 1);
            //将发票号和发票流水号分割成数组
            string[] arrayInvoiceSerialId = hidinvoice.Replace("'", "").Split(',');
            string[] arrayInvoiceId = invoiceId.Split(',');
            //将已选的发票加入到列表中
            for (int i = 0; i < arrayInvoiceId.Length; i++)
            {
                Invoice tmpInvoice = new Invoice();
                tmpInvoice.InvoiceID = arrayInvoiceId[i];
                tmpInvoice.InvoiceSerialID = arrayInvoiceSerialId[i];
                lstInvoice.Add(tmpInvoice);
            }
            //foreach (string invo in hidinvoice.Replace("'","").Split(','))
            //{   
            //       Invoice tmpInvoice = new Invoice ();
            //       tmpInvoice.InvoiceSerialID = invo;
            //       lstInvoice.Add (tmpInvoice);
            //}

            try
            {
                int state = iPurchase.SelectInvoiceStates(InvoicePaySerialID);
                if (state == 1)
                {
                    HZ.Web.WebUtil.Alert("结算单已确认，无法进行修改!", this);
                    HZ.Web.WebUtil.RedirectByScript("BulidPaymentManage.aspx");
                    return;
                }
                else
                {
                    if (Request.QueryString["IID"] != null)//更新
                    {
                        int nSuccessUpdate = iPurchase.UpdateInvoicePay_Detail(aInvoicePay, lstInvoice);
                        if (nSuccessUpdate == 1)
                        {
                            HZ.Web.WebUtil.Alert("结算单已更新成功!", this);
                            //HZ.Web.WebUtil.RedirectByScript("BulidPaymentAdd.aspx");
                            HZ.Web.WebUtil.RedirectByScript("BulidPaymentManage.aspx");
                            //return;
                        }
                        else
                        {
                            HZ.Web.WebUtil.Alert("结算单更新失败!", this);
                            return;
                        }
                    }
                    int nSuccess = iPurchase.AddInvoicePay(aInvoicePay, lstInvoice);
                    if (nSuccess == 1)
                    {
                        HZ.Web.WebUtil.Alert("结算单已成功添加!", this);
                        //HZ.Web.WebUtil.RedirectByScript("BulidPaymentAdd.aspx");
                        HZ.Web.WebUtil.RedirectByScript("BulidPaymentManage.aspx");
                        //return;
                    }
                    else
                    {
                        HZ.Web.WebUtil.Alert("结算单添加失败!", this);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                HZ.Web.WebUtil.Alert(ex.Message);
                return;
            }

        }



    }
}
